有沒有需要在app中加入月曆的情況呢?這時是不是會覺得不知如何是好,別擔心!我找到了超好用的方法今天就分享給你知道~那就是「FSCalendar」有了他就可以快速產生月曆,還能夠使用各種擴充功能讓你的月曆更完整喔。
在Storyboard加入一個View,class輸入FSCalendarView Controller要繼承FSCalendarDelegate, FSCalendarDataSource以及import FSCalendar
(範例檔:CalendarViewController.swift)
import UIKit
import FSCalendar
import FirebaseAuth
import FirebaseFirestore
import Firebase
import CoreData
class CalendarViewController: UIViewController,FSCalendarDelegate, FSCalendarDataSource {
let db = Firestore.firestore()
let userID = Auth.auth().currentUser!.uid
var dateString = ""
//紀錄有事件的日期,依據事件數量分為兩個
var datesWithEvent = [String]()//小於等於3件事
var datesWithMultipleEvents = [String]()//大於3件事
//連結到Storyboard剛剛新增的FSCalendar
@IBOutlet var calendar: FSCalendar!
override func viewDidLoad() {
super.viewDidLoad()
loadDateEvent()
calendar.delegate = self
calendar.dataSource = self
calendar.appearance.headerTitleColor = UIColor(hexString: "#3D538B")
calendar.today = nil
calendar.appearance.selectionColor = UIColor(hexString: "#6687AD")
calendar.appearance.weekdayTextColor = UIColor(hexString: "#3D538B")
}
override func viewWillAppear(_ animated: Bool) {
loadDateEvent()
//重載calendar.資料
calendar.reloadData()
}
override func viewDidDisappear(_ animated: Bool) {
datesWithEvent = []
datesWithMultipleEvents = []
}
//設定日期格式
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
func loadDateEvent(){
let context = CoreDataManager.shared.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<User>(entityName: "User")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "firestoreID == %@", userID)
do{
let Userexist = try context.fetch(fetchRequest)
let fetchRequest2 = NSFetchRequest<DateInfo>(entityName: "DateInfo")
fetchRequest2.predicate = NSPredicate(format: "uuid == %@", Userexist[0].uuid! as CVarArg)
do{
let dateInfoexist = try context.fetch(fetchRequest2)
for i in dateInfoexist{
var dateRemoveWeekofMonth = i.date!.dropLast()
dateRemoveWeekofMonth = dateRemoveWeekofMonth.dropLast()
if(6-Int(i.eventCount) != 0 && 6-Int(i.eventCount) < 4){
datesWithEvent.append(String(dateRemoveWeekofMonth))
}else if ((6-Int(i.eventCount) > 3)){
datesWithMultipleEvents.append(String(dateRemoveWeekofMonth))
}
}
}catch let fetchError{
print("Failed to fetch compaies: \(fetchError)")
}
}catch let fetchError{
print("Failed to fetch User: \(fetchError)")
}
}
}
//點擊事件時
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
//跳出當天紀錄
dateString = self.dateFormatter2.string(from: date)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let secondVC = storyboard.instantiateViewController(identifier: Constants.Storyboard.eventViewController) as? EventViewController{
let backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backBarButtonItem
secondVC.dateS = dateString
show(secondVC, sender: self)
}
}
//事件圖片設定
func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {
let dateString = self.dateFormatter2.string(from: date)
//小於等於3件事要顯示的圖片
if self.datesWithEvent.contains(dateString) {
return UIImage(named: "圖片名稱")!.resized(to: CGSize(width: 35, height: 35))
}
//大於3件事要顯示的圖片
if self.datesWithMultipleEvents.contains(dateString) {
return UIImage(named: "圖片名稱")!.resized(to: CGSize(width: 35, height: 35))
}
return nil
}
參考出處:https://stackoverflow.com/questions/2658738/the-simplest-way-to-resize-an-uiimage
extension UIImage {
func resized(to size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
}
有了FSCalendar真的對開發有了大大的幫助,除了上面有介紹到的部分還有很多功能等大家去發掘唷!除了程式可以對月曆做設定,也能在Storyboard直接設定唷~
參考出處:https://github.com/WenchaoD/FSCalendar
參考出處:https://juejin.im/post/6844903933840736263